package com.yzh.wanandroid.network.retrofit

import com.google.gson.Gson
import com.yzh.wanandroid.network.interceptor.HeaderInterceptor
import com.yzh.wanandroid.network.interceptor.SaveCookieInterceptor
import com.yzh.wanandroid.utils.DEFAULT_TIMEOUT
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class RetrofitFactory private constructor() {

    private val mRetrofit: Retrofit

    init {
        val gson = Gson().newBuilder()
            .setLenient()
            .serializeNulls()
            .create()
        mRetrofit = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(getOkHttpClient())
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()
    }

    // 单例模式
    companion object {
        private val INSTANT : RetrofitFactory by lazy (mode = LazyThreadSafetyMode.SYNCHRONIZED){ RetrofitFactory() }

        private fun get() : RetrofitFactory{
            return INSTANT
        }

        fun <T> createApi(tClass: Class<T>): T {
            return  lazy (mode = LazyThreadSafetyMode.SYNCHRONIZED){ get().createApi(tClass) }.value
        }
    }

    private fun <T> createApi(tClass: Class<T>): T {
        return mRetrofit.create(tClass)
    }

    private fun getOkHttpClient(): OkHttpClient {
        val builder = OkHttpClient().newBuilder()
        //设置 请求的缓存的大小跟位置
//        val cacheFile = File(MainApplication.appContext.cacheDir, "cache")
//        val cache = Cache(cacheFile, MAX_CACHE_SIZE)
        builder.run {
            addInterceptor(HeaderInterceptor())
            addInterceptor(SaveCookieInterceptor())
//            addInterceptor(CacheInterceptor(cache))
            connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
            readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
            writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
            retryOnConnectionFailure(true) // 错误重连
        }
        return builder.build()
    }
}